/*
 * @LastEditTime: 2023-02-28 11:30:54
 */
import { Lyrics } from "../Models/Lyrics.schema";
import { createLyricsDTO, updateLyricsDTO } from "../DTO/Lyrics.dto";

export class LyricsController {
  constructor(private readonly lyricsModel: typeof Lyrics) { }

  /**
   * 创建歌词
   * @param dto 数据传输对象
   * @returns 返回创建对象
   */
  async createItem(dto: createLyricsDTO) {
    try {
      return {
        code: 200,
        message: "创建成功",
        data: await this.lyricsModel.create(dto),
      };
    } catch (error) {
      return await error;
    }
  }

  /**
   * 以ID为查找依据删除歌词
   * @param id 要删除元素的唯一ID
   * @returns
   */
  async removeById(id: string) {
    try {
      if (!await this.isExistsforId(id)) {

        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "删除成功",
          data: await this.lyricsModel.deleteOne({ _id: id }),
        };
      }
    } catch (error) {
      return await error;
    }
  }

  /**
   * 按ID更新歌词
   * @param id 要更新的ID
   * @param dto  要更新的内容
   * @returns 更新对象
   */
  async updateById(id: string, dto: updateLyricsDTO) {
    try {
      if (!await this.isExistsforId(id)) {
        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "更新成功",
          data: await this.lyricsModel.updateOne({ _id: id }, dto),
        };
        console.log(1);
      }
    } catch (error) {
      return await error;
    }
  }
  /**
   * 按ID查找歌词
   * @param id 要查找的歌词名称
   * @returns 查询对象
   */
  async findById(id: string) {
    try {
      if (!await this.isExistsforId(id)) {

        return {
          code: 400,
          message: '不存在查询的ID',
        }
      } else {
        return {
          code: 200,
          message: "查询成功",
          data: await this.lyricsModel.find({ _id: id }),
        };
      }
    } catch (error) {
      return false;
    }
  }


  async isExistsforId(id: string): Promise<boolean> {
    try {
      const res: number = await this.lyricsModel.find({ _id: id }).count();
      if (res === 0) {
        return false;
      }
      return true;
    } catch (error) {
      return false;
    }
  }
  async isExistsforTitle(title: string): Promise<boolean> {
    try {
      const res: number = await this.lyricsModel.find({ title: title }).count();
      if (res === 0) {
        return false;
      }
      return true;
    } catch (error) {
      return false;
    }
  }
}